package com.foo.DataStore;

import javax.annotation.Resource;
import javax.ejb.ActivationConfigProperty;
import javax.ejb.MessageDriven;
import javax.ejb.MessageDrivenContext;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.ObjectMessage;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueSession;
import javax.jms.TextMessage;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceUnit;
import javax.persistence.Query;

import java.sql.Date;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;

import com.foo.DAO.DataStoreDAO;
import com.foo.Entity.*;
import javax.jms.*;
import javax.naming.*;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.Properties;


/**
 * Message-Driven Bean implementation class for: StockRecorder
 * Author: Deepika Gohil
 */
@MessageDriven(
		activationConfig =
		{ @ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue"),
		@ActivationConfigProperty(propertyName = "destination", propertyValue = "queue/HistoricalDataStorage"),
		@ActivationConfigProperty(propertyName= "transactionTimeout", propertyValue ="1500")		
		})

public class StockRecorder implements MessageListener {

	@Resource // used for rollback of the message in case of any inconsistency. 
	MessageDrivenContext mdc;
	
	//@PersistenceContext(unitName="stockprovider")
	EntityManager em;

	private Session session;
	private Connection connection;
	private HistoricalData stockData = null;
	
    public StockRecorder() 
    {	
    	try
    	{
    	Properties props = new Properties();
		props.put(Context.PROVIDER_URL, "jnp://localhost:1099");
		props.put(Context.INITIAL_CONTEXT_FACTORY,"org.jnp.interfaces.NamingContextFactory");
		props.put(Context.URL_PKG_PREFIXES,"org.jboss.naming:org.jnp.interfaces");
		Context ctx = new InitialContext(props);
		ConnectionFactory factory = (QueueConnectionFactory) ctx.lookup("XAConnectionFactory");
		connection = factory.createConnection();
		session = connection.createSession(false, QueueSession.AUTO_ACKNOWLEDGE);
    	}
    	catch(Exception JMSE)
		{
			System.out.println("JMS Exception: "+JMSE);
		}
    	
    }
	
	/**
     * @see MessageListener#onMessage(Message)
     */
    public void onMessage(Message message) 
    {
    	int flag = 0;
    	if(message instanceof ObjectMessage)
    	{
    	System.out.println("Message Reading from Queue!!!!!!!!!!");
    	try
    	{
    		ObjectMessage msg = (ObjectMessage) message;
    		HistoricalData[] historicalData = (HistoricalData[])msg.getObject();
    		DataStoreDAO forumDAO = null;
    		
    		if(historicalData != null)
    		{
    			int numOfRecords = historicalData.length;
        		
    			ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
    			forumDAO = (DataStoreDAO) context.getBean("datastoreDAO");
        		forumDAO.insertForum(historicalData,numOfRecords);		
    		}
    		else
    		{
    			System.out.println("No Historical Data Obtained!!! ");
    		}
    		System.out.println("Historical Table updated!");
    		//sendReply(message, flag);
    		
    		//Update the percentage change
    		if(forumDAO !=null)
    		{
    			forumDAO.updateforum();
    		}
    	}
    	catch(Exception e)
    	{
    		System.out.println("Exception occured while recording new Stock Data.");
    		e.printStackTrace();
    		mdc.setRollbackOnly();
    	}      
    	}
    }
    
    // send reply as 1 if data successfully stored
    // or send reply as 0.
    /*public void sendReply(Message request, int flag)
	{
		try
		{
			MessageProducer MP = session.createProducer(null);
			Destination reply = request.getJMSReplyTo();
			TextMessage TM = session.createTextMessage();
			TM.setText(""+flag);
			MP.send(reply, TM);
		}
		catch(Exception JMSE)
		{
			System.out.println("JMS Exception: "+JMSE);
		}
	}*/
}
